package com.yplan.dm;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SocketClientManager {

    //Socket连接
    private static Socket client;

    //Socket的输出流，用来发送数据到服务端
    private static PrintStream out;

    //Socket的输入流，用来接收从服务端发送过来的数据
    private static BufferedReader buf;

    private String ip;
    private int port;
    private JTextArea area;

    public SocketClientManager(String ip, int port, JTextArea area) {
        try {
            this.ip = ip;
            this.port = port;
            this.area = area;
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() {
        try {
            client = new Socket(ip, port);
            //获取Socket的输出流
            out = new PrintStream(client.getOutputStream());
            //获取Socket的输入流
            buf = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
        } catch (Exception e) {
            DanmuHelper.log("err::" + e.getMessage());
            out = null;
            client = null;
            buf = null;
            if (area != null) area.append("连接失败，请检查是否开启游戏服务\n");
            e.printStackTrace();
        }
    }

    public void send(String msg, JTextArea textArea) {
        if (textArea != null) {
            textArea.append("socket转发数据------------------------------------------\n");
            textArea.append(msg + "\n");
            textArea.append("\n");
        }
        send(msg);
    }

    public void send(String msg) {
        if (out == null) return;
        try {
            //发送数据到服务端
            out.println(msg);
            out.flush();
            DanmuHelper.log("send::::" + msg);
        } catch (Exception e) {
            //打印日志，并重连Socket
            System.err.println("Socket连接异常，正在重新连接...");
            e.printStackTrace();

            init();
            if (out != null) {
                //重新发送数据数据到服务端
                out.println(msg);
                out.flush();
            }
            DanmuHelper.log("send::::" + msg);
        }
    }

    public void close() {
        //通知服务端结束与客户端的连接异步线程
        try {
            out.println("exit");
            out.flush();
            out.close();
            buf.close();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
